<?php
namespace BoxAdmin\Controller;

use Think\Controller;

class CardController extends CommonController
{
    public function _initialize()
    {
        $this->memuNav = "index";
        parent::_initialize();
        $this->stateArray = array(
            1 => '未激活',
            2 => '已激活',
            3 => '冻结',
            4 => '作废',
            5 => '已使用'
        );
        $this->card = BoxModel('SystemCard');
        //dump($_SESSION);

    }

    function index()
    {
        // echo MODULE_NAME;
        $mintime = I('get.mintime');
        $maxtime = I('get.maxtime');
        $minmoney = I('get.minmoney');
        $maxmoney = I('get.maxmoney');
        $storeList = BoxModel("store")->where("isOpen=1")->select();
        foreach ($storeList as $one) {
            $storeList1[$one['store_id']] = $one;
        }
        $this->storeList = $storeList1;
        $date = strtotime("-1 year");
        //dump($date);
        $where = "(C.bing_time>'$date' or C.bing_time=0)";
        if ($this->store_id = I('store_id')) {
            $where .= " and C.store_id='$this->store_id'";
        }
        if ($this->kw = I('kw')) {
            $where .= " and (C.num like '%$this->kw%' or S.store_name like '%$this->kw%' or C.seller like '%$this->kw%' or C.store_user_name like '%$this->kw%' or C.company like '%$this->kw%' )";
        }
        if ($this->state = I('state')) {
            $where .= " and C.state='$this->state'";
        }
        if ($this->recharge = I('recharge')) {
            $where .= " and C.state=5";
        }
        if (!empty($mintime) && !empty($maxtime)) {
            $where .= " and  '$mintime' <= C.invalid_time && '$maxtime' >=  C.invalid_time";
        }
        $s_addtime = I('s_addtime');
        $e_addtime = I('e_addtime');
        if (!empty($s_addtime) && !empty($e_addtime)) {
            $where .= " and  '$s_addtime' <= C.addtime && '$e_addtime' >=  C.addtime";
        }
        $s_recharge_time = I('s_recharge_time');
        $e_recharge_time = I('e_recharge_time');
        if (!empty($s_recharge_time) && !empty($e_recharge_time)) {
            $where .= " and  '$s_recharge_time' <= C.recharge_time && '$e_recharge_time' >=  C.recharge_time";
        }
        $s_bing_time = I('s_bing_time');
        $e_bing_time = I('e_bing_time');
        if (!empty($s_bing_time) && !empty($e_bing_time)) {
            $where .= " and  '$s_bing_time' <= C.bing_time && '$e_bing_time' >=  C.bing_time";
        }
        if (!empty($minmoney) && !empty($maxmoney)) {
            $where .= " and (C.money >= '$minmoney' and C.money <= '$maxmoney')";
        }
        $export = I('export');
        if ($export) {
            $this->data = $this->card->alias("C")->where($where)->field("C.*")->join(" left join system_store as S on C.store_id=S.store_id")->order("C.id desc")->select();
            //dump($this->data);
            //dump( $this->card);exit();
            /*******导出卡券未消费的*******/
            if ($export == 1) {
                $p = array('卡号', '密码', '电商平台', '卡金额', '生成时间', '过期时间', '生成人', '销售人员', '销售公司', '状态');
                foreach ($this->data as $key => $one) {
                    $data[$key]['num'] = $one['num'];
                    $data[$key]['password'] = " " . $one['password'];
                    $data[$key]['store_name'] = $this->storeList[$one['store_id']]['store_name'];
                    $data[$key]['money'] = $one['money'];
                    $data[$key]['addtime'] = $one['addtime'];
                    $data[$key]['invalid_time'] = $one['invalid_time'];
                    $data[$key]['store_user_name'] = $one['store_user_name'];
                    $data[$key]['seller'] = $one['seller'];
                    $data[$key]['company'] = $one['company'];
                    $data[$key]['state'] = $this->stateArray[$one['state']];
                }
            }
            /*******导出卡券绑定用户的*******/
            if ($export == 2) {
                $p = array('卡号', '密码', '电商平台', '用户名', '卡金额', '生成时间', '过期时间', '生成人', '销售人员', '销售公司', '状态', '绑定时间', '消费时间', '邮箱', '电话', '姓名');
                foreach ($this->data as $key => $one) {
                    $user = BoxModel("member")->find($one['user_id']);
                    $data[$key]['num'] = $one['num'];
                    $data[$key]['password'] = " " . $one['password'];
                    $data[$key]['store_name'] = $this->storeList[$one['store_id']]['store_name'];
                    $data[$key]['money'] = $one['money'];
                    $data[$key]['user_id'] = $user['user_name'];
                    $data[$key]['addtime'] = $one['addtime'];
                    $data[$key]['invalid_time'] = $one['invalid_time'];
                    $data[$key]['store_user_name'] = $one['store_user_name'];
                    $data[$key]['seller'] = $one['seller'];
                    $data[$key]['company'] = $one['company'];
                    $data[$key]['state'] = $this->stateArray[$one['state']];
                    $data[$key]['bing_time'] = date("Y-m-d H:i:s", $one['bing_time']);
                    $data[$key]['recharge_time'] = $one['recharge_time'];
                    $data[$key]['email'] = $user['email'];
                    $data[$key]['phone'] = $user['phone'];
                    $data[$key]['name'] = $user['name'];
                }
            }
            $this->export($p, $data);
        }
        $count = $this->card->alias("C")->where($where)->join(" left join system_store as S on C.store_id=S.store_id")->count();
        //dump($this->card);
        $this->setPager($count, 8);
        $this->data = $this->card->alias("C")->where($where)->field("C.*")->join(" left join system_store as S on C.store_id=S.store_id")->order("addtime desc")->limit($this->limit)->select();
        //	dump($this->card);
        //dump($this->data);
        if ($recharge = I('recharge')) { //充值记录
            $this->memuNav = "recharge";
            foreach ($this->data as $k => $one) {
                $data[$k] = $one;
                $data[$k]['user'] = BoxModel("SystemMember")->load($one['user_id']);
            }
            //dump($data);
            $this->data = $data;
            $this->display("recharge");
        } else {
            $this->display("index");
        }
    }

    function import()
    {
        $this->memuNav = "add";
        if (IS_POST) {
            $file = $_FILES['excel']['tmp_name'];
            if ($file) {
                ini_set('memory_limit', '1280M');
                set_time_limit(0);
                $obj = new \Common\Org\icPHPExcel();
                $obj->Load_Excel($file);
                $data = $obj->findAll();
                $sucees = 0;
                $fail = 0;
                unset($data[1]);
                //dump($data);exit();
                $model = BoxModel("store");
                foreach ($data as $value) {
                    $error = "";
                    $store_name = $value['C'];
                    $store_info = $model->where("store_name='$store_name'")->find();
                    if (!$store_info['store_id']) {
                        $error = "原因：电商平台不正确";
                    }
                    $row = array(
                        'money' => $value['D'],
                        'addtime' => $value['E'],
                        'invalid_time' => $value['F'],
                        'store_user_name' => $value['G'],
                        'company' => $value['I'],
                        'seller' => $value['H'],
                        'updatetime' => date("Y-m-d H:i:s"),
                        'store_id' => $store_info['store_id'],
                    );
                    $where = array('num' => $value['A']);
                    if (!$error) {
                        $id = $this->card->where($where)->save($row);
                    }
                    //dump($this->card);
                    if ($id) {
                        $sucees++;
                        $r = "成功";
                        $class = "suc";
                    } else {
                        $fail++;
                        $r = "失败" . $error;
                        $class = "fail";
                    }
                    $msg2 .= "<p class='" . $class . "'>导入" . $r . "，卡号：" . $value['A'] . "</p>";
                }
                $this->msg = $msg2;
                $this->sucees = $sucees;
                $this->fail = $fail;
                $this->display("import_msg");
                exit();
            }
        }
        $this->display("import");
    }

    /****批量生成卡券**/
    function add()
    {
        $this->memuNav = "add";
        $this->storeList = BoxModel("store")->where("isOpen=1")->select();
        $this->display();
    }

    function add_act()
    {
        $num = I("number", "0", "intval");
        $money = I("money", "0", "intval");
        $point = I("invalid_time", "0", "invalid_time");
        $this->store_id = I('store_id');
        if ($num == 0) return;
        $num = $num; //卡的张数，即记录数
        for ($i = 1; $i <= $num; $i++) {
            $sn = createCardNo(i);
            $seek = mt_rand(0, 9999) . mt_rand(0, 9999) . mt_rand(0, 9999); //12位
            $start = mt_rand(0, 20);
            $str = strtoupper(substr(md5($seek), $start, 12));
            $str = str_replace("O", chr(mt_rand(65, 78)), $str);
            $str = str_replace("0", chr(mt_rand(65, 78)), $str);
            $row = array(
                'num' => $sn,
                'password' => $str,
                'addtime' => date("Y-m-d H:i:s"),
                'money' => $money,
                'store_user_name' => $_SESSION['admin_user_name'],
                'store_id' => $this->store_id,
                'invalid_time' => I('invalid_time'),
                'seller' => I('seller'),
                'company' => I('company'),
            );
            //查重
            //在这里加插入数据的代码.
            $this->card->add($row);
        }
        $this->jump("操作成功", U('index'));
    }

    /**
     * 生成随机数
     */
    public function great_rand($n = 30)
    {
        $str = '1234567890abcdefghijklmnopqrstuvwxyz';
        for ($i = 0; $i < $n; $i++) {
            $j = rand(0, 35);
            $t1 .= $str[$j];
        }
        return $t1;
    }

    /**************卡状态修改****/
    function stateact()
    {
        $ids = I('ids');
        $state = I('state', "", "intval");
        $ids = explode(",", $ids);
        foreach ($ids as $id) {
            $data = $this->card->find($id);
            if ($data['state'] < 4) $this->card->where("id='$id'")->save(array(
                'state' => $state
            ));
        }
        $this->jump("操作成功");
    }

    /*****导出**/
    function export($titles, $data, $name = "")
    {
        $objPHPExcel = new \Common\Org\icPHPExcel();
        $objPHPExcel->create_from_mysql($titles, $data);
        $name = $name ? $name : date("YmdH") . "_卡券使用记录.xls";
        $filepath = APP_PATH . "/Runtime/" . $name;
        $objPHPExcel->saveExcel($filepath);
        // header("Location: /Application/Runtime/" . $name);
        down($filepath);
    }

}

?>